/*
 * @Author: Liuxin 2849181826@qq.com
 * @Date: 2025-04-03 09:26:37
 * @LastEditors: Liuxin 2849181826@qq.com
 * @LastEditTime: 2025-04-14 21:57:01
 * @FilePath: \node-exe\electron-vite-vue\src\puppeteer_ads\config\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Store from "electron-store"
import path from "path"
import os from "os"
import pkg from "node-machine-id"
const { machineId, machineIdSync } = pkg
const idSync = machineIdSync() // 同步
console.log("同步获取ID:", idSync)
export const mqttConfig = {
  account: idSync,
  platform: "headLess",
  tenantId: 2,
}
export let adsConfig = null

// 添加BiMap实现
export function createBiMap() {
  const map = new Map()
  const reverseMap = new Map()

  return {
    set(key, value) {
      map.set(key, value)
      reverseMap.set(value, key)
    },
    get(key) {
      return map.get(key)
    },
    getKey(value) {
      return reverseMap.get(value)
    },
    has(key) {
      return map.has(key)
    },
    hasValue(value) {
      return reverseMap.has(value)
    },
    delete(key) {
      const value = map.get(key)
      map.delete(key)
      reverseMap.delete(value)
    },
    keys() {
      return map.keys()
    },
    values() {
      return map.values()
    },
    clear() {
      map.clear()
      reverseMap.clear()
    },
    size() {
      return map.size
    },
  }
}

// 全局配置信息
export let configMap = createBiMap()

// 创建用于读取Store的函数
export function createNamedStore(name) {
  return new Store({
    name,
    defaults: {},
    // 与Electron主进程保持一致的关键配置 - 指定相同的项目名称
    projectName: "electron-store-nodejs",
    // 指定相同的配置文件夹名称
    cwd: path.join(os.homedir(), "AppData", "Roaming", "electron-store-nodejs", "Config"),
  })
}

// 读取来自electron-store的窗口数据
let windowsData = null
try {
  // 环境变量中的TASK_ID应该是"windowRunData"
  const storeKey = process.env.TASK_ID || "windowRunData"
  const automationTasksStore = createNamedStore("automation-tasks")
  const storeData = automationTasksStore.get(storeKey)

  if (storeData && storeData.data) {
    try {
      // 数据可能是字符串也可能是对象
      if (typeof storeData.data === "string") {
        windowsData = JSON.parse(storeData.data)
      } else {
        windowsData = storeData.data
      }
      console.log("[配置] 成功从electron-store读取窗口数据")
    } catch (e) {
      console.error("[配置] 解析窗口数据失败:", e)
    }
  } else {
    console.error("[配置] electron-store中没有找到有效的窗口数据")
  }
} catch (e) {
  console.error("[配置] 读取electron-store时出错:", e)
}

// 导出windowsData供其他模块使用
export { windowsData }

/**
 * 从Vue应用传递的设备列表生成adsConfig格式的配置
 * @param {Array} deviceIdList 设备列表数据
 * @returns {Object} adsConfig格式的配置对象
 */
export function generateAdsConfig(deviceIdList, mode) {
  console.log("generateAdsConfig", deviceIdList, mode)
  if (!deviceIdList || !Array.isArray(deviceIdList) || deviceIdList.length === 0) {
    return adsConfig // 返回默认配置
  }

  const newConfig = {}

  deviceIdList.forEach((device, index) => {
    if (device) {
      // 索引从1开始
      newConfig[`userId_${mode}${index + 1}`] = device
    }
  })
  adsConfig = newConfig
  console.log("newConfig", newConfig)
  return newConfig
}

export const mqttBaseURLConfig = {
  ["development"]: {
    host: "35.95.209.213",
    port: 8834,
    username: "mqttweb",
    password: "X@Ap3jHfh&~",
    clientId: `mqtt_${mqttConfig.account}`,
    connectOptions: {
      keepalive: 30,
      reconnectPeriod: 30 * 1000,
      clean: false,
    },
  },
  ["test"]: {
    host: "35.95.209.213",
    port: 8834,
    username: "mqttweb",
    password: "X@Ap3jHfh&~",
    clientId: `mqtt_${mqttConfig.account}`,
    connectOptions: {
      keepalive: 30,
      reconnectPeriod: 30 * 1000,
      clean: false,
    },
  },
  ["production"]: {
    host: "44.240.80.74",
    port: 8834,
    username: "mqttweb",
    password: "X@Ap3jHfh&~",
    clientId: `mqtt_${mqttConfig.account}`,
    connectOptions: {
      keepalive: 30,
      reconnectPeriod: 30 * 1000,
      clean: false,
    },
  },
}
export const appBaseURKConfig = {
  ["development"]: "http://35.95.209.213:8563",
  ["test"]: "http://35.95.209.213:8563",
  ["production"]: "http://44.240.80.74:8563",
}
// 全局窗口与执行的任务绑定map
export const windowIdOfTask = {}
// 获取命令行参数
const args = process.argv.slice(2)
export const params = {}
args
  .filter((arg) => arg !== "--") // 过滤掉 '--'
  .forEach((arg) => {
    const [key, value] = arg.split("=") // 使用 '=' 分隔
    if (key && value) {
      // 确保存在键和值
      params[key] = value
    }
  })
// vue传来的action有：runTask:运行业务任务 bindAccount:绑定业务账号
const { mode, windowRunData } = params
console.log(`[自动化服务] 启动模式: ${mode}, 任务ID: ${windowRunData}`)

// 验证数据是否有效
if (!windowsData) {
  console.error("[自动化服务] 无法获取有效的窗口数据，退出自动化服务")
  process.exit(1)
}

